package com.hewl.shiro.admin.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.hewl.shiro.admin.dao.RoleMapper;
import com.hewl.shiro.admin.entity.SysUser;

@Controller
public class ShiroController {

	private static Logger logger = LoggerFactory.getLogger(ShiroController.class);

	@Autowired
	private RoleMapper roleMapper;

	@GetMapping("/login")
	public String login(HttpServletRequest request, Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		model.addAttribute("projectName", "MOXI");
		System.out.println(session);
		return "login";
	}

	@GetMapping("/register")
	public String register(Model model) {
		model.addAttribute("projectName", "MOXI");
		return "register";
	}

	@GetMapping("/index")
	public String index(Model model) {
		return "index";
	}

	@GetMapping("/organization")
	public String organization(Model model) {
		return "organization";
	}

	@GetMapping("/resource")
	public String resurce(Model model) {
		return "resource";
	}

	@GetMapping("/permission")
	public String permission(Model model) {
		return "permission";
	}

	@GetMapping("/role")
	public String role(Model model) {
		return "role";
	}

	@GetMapping("/user")
	public String user(Model model) {
		return "user";
	}

	@GetMapping("/system")
	public String system(Model model) {
		return "system";
	}

	@GetMapping("/role/index")
	@RequiresRoles(value = { "888888", "user" }, logical = Logical.OR)
	@RequiresPermissions(value = { "/role/index", "update" }, logical = Logical.OR)
	public String success(HttpServletRequest request, Model model) {
		// 获取到用户信息;
		Subject subject = SecurityUtils.getSubject();
		SysUser user = (SysUser) subject.getPrincipal();
		model.addAttribute("userInfo", user);
		return "success";
	}

	/**
	 * ajax登录请求接口方式登陆
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@PostMapping("/checkLogin")
	public String submitLogin(HttpServletRequest request, String username, String password, String rememberMe,
			String code, Model model) {
		try {
			if(!ObjectUtils.isEmpty(code)) {
				String verifyCode = (String) request.getSession().getAttribute("verifyCode");
				if(!code.equals(verifyCode)) {
					logger.info("验证码输入有误");
					model.addAttribute("msg", "验证码输入有误");
					return "login";
				}
			}
			// 使用 Shiro 对密码进行加密
			Md5Hash hash = new Md5Hash(password, username, 2);
			UsernamePasswordToken token = new UsernamePasswordToken(username, hash.toString());
			Subject currentUser = SecurityUtils.getSubject();
			if (!currentUser.isAuthenticated()) {
				// 使用shiro来验证
				if (rememberMe != null && rememberMe.equals("1")) {
					token.setRememberMe(true);
				} else {
					token.setRememberMe(false);
				}
				currentUser.login(token);// 验证角色和权限
			}
			SysUser user = (SysUser) currentUser.getPrincipal();
			request.getSession().setAttribute("userInfo", user);
			return "redirect:/index";
		} catch (UnknownAccountException e) {
			logger.info("账户不存在");
			model.addAttribute("msg", "账号不存在");
		} catch (IncorrectCredentialsException e) {
			logger.info("密码错误");
			model.addAttribute("msg", "密码错误");
		} catch (Exception e) {
			model.addAttribute("msg", "服务器错误");
		}
		return "redirect:/login";

	}

}
